#include "canctrl.h"
#include <QGlobalStatic>
#include <QDebug>

Q_GLOBAL_STATIC(CANCtrl,m_instance)

CANCtrl::CANCtrl(QObject *parent)
    : QObject{parent}
{}

CANCtrl *CANCtrl::Instance()
{
    return m_instance;
}

bool CANCtrl::initCAN(DWORD deviceType, DWORD deviceIndex, DWORD channel)
{
    if (VCI_OpenDevice(deviceType, deviceIndex, 0) != 1) {
        qDebug() << "CAN" << channel << "设备打开失败";
        return false;
    }

    VCI_INIT_CONFIG config;
    config.AccCode = 0x00000000; //接收所有报文
    config.AccMask = 0xFFFFFFFF; //所有单位都需要匹配
    config.Filter = 1;           //启用单过滤器模式
    //config.Reserved = 0;         //保留字段设置为0
    config.Mode = 0;             //正常模式
    config.Timing0 = 0x01;       //波特率参数0
    config.Timing1 = 0x1C;       //波特率参数1（500kbps）

    if (VCI_InitCAN(deviceType, deviceIndex, channel, &config) != 1) {
        qDebug() << "CAN" << channel << "初始化失败";
        return false;
    }

    if (VCI_StartCAN(deviceType, deviceIndex, channel) != 1) {
        qDebug() << "CAN" << channel << "启动失败";
        return false;
    }

    qDebug() << "CAN" << channel << "初始化成功";
    return true;
}

void CANCtrl::sendCANData(DWORD deviceType, DWORD deviceIndex, DWORD channel, DWORD id, BYTE *data, DWORD len)
{
    VCI_CAN_OBJ canObj;
    canObj.ID = id;
    canObj.SendType = 0;
    canObj.RemoteFlag = 0;
    canObj.ExternFlag = 0;
    canObj.DataLen = len;
    memcpy(canObj.Data, data, len);

    if (VCI_Transmit(deviceType, deviceIndex, channel, &canObj, 1) == 1) {
        qDebug() << "CAN" << channel << "数据发送成功, ID:" << id;
    } else {
        qDebug() << "CAN" << channel << "数据发送失败";
    }
}

void CANCtrl::receiveCANData(DWORD deviceType, DWORD deviceIndex, DWORD channel)
{
    VCI_CAN_OBJ canObj[10];
    DWORD len = VCI_Receive(deviceType, deviceIndex, channel, canObj, 10, 0);
    if (len > 0) {
        for (DWORD i = 0; i < len; i++) {
            qDebug() << "CAN" << channel << "接收到数据, ID:" << canObj[i].ID
                     << "数据:" << QByteArray((char*)canObj[i].Data, canObj[i].DataLen).toHex();
        }
    }
}
